#!/usr/bin/env python
#-*- coding:utf-8 -*-

from __future__ import absolute_import
from celery import task
import urllib
import urllib2
import cookielib
from grap.plugins import mysql_check
from zabbix_grap import settings
from grap import models
import threading
import datetime

cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
h = urllib2.urlopen(settings.hosturl)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1',
           'Referer': '******'}
postData = urllib.urlencode(settings.postData)
request = urllib2.Request(settings.posturl, postData, headers)
response = urllib2.urlopen(request)
text = response.read()


def get_graph(host, graphid,period, image_name):
    path = './static/image/'  # 保存图片的地址
    # zabbix的图片的地址的构造
    url = "%s/chart2.php?graphid=%s&period=%s&width=800&height=100" % (host, graphid,period )

    img_req = urllib2.Request(url)
    png = urllib2.urlopen(img_req).read()

    file = path + image_name + '.png'
    with open(file, 'wb') as f:
        f.write(png)

def update_zabbix(id,name):
    print int(id)
    get_graph(settings.zabbix_url,int(id), settings.zabbix_time, str(id))
    dev_up = models.Device.objects.get_or_create(graphid=str(id), )
    dev_up[0].name = name
    dev_up[0].save()


def Compared():
    biaozhun =[]
    xinde = []
    data2 = mysql_check.MysqlHelper().Get_all(sql="select graphid from graphs where name like '%汇总%';")
    for i in data2:
        biaozhun.append(int(i[0]))
    data3 =  models.Device.objects.all().values('graphid')
    for i in data3:
        xinde.append(int(i['graphid']))
    result = [l for l in xinde if l not in biaozhun]
    if result:
        print '处理多余图形'
        for i in result:
            models.Device.objects.filter(graphid=i).delete()


@task
def get_zabbix():
    print '开始更新数据'
    begin = datetime.datetime.now()
    threads = []
    data = mysql_check.MysqlHelper().Get_all(sql="select graphid,NAME from graphs where name like '%汇总%';")
    if data == False:
        print 'ERROR,数据库连接失败，或网络不可达！'
        return False
    for i in data:
        threads.append(threading.Thread(update_zabbix(i[0],i[1])))
    for t in threads:
        t.start()
    # 主线程中等待所有子线程退出
    for t in threads:
        t.join()
    print '更新完成'
    end = datetime.datetime.now()
    print '处理时间:%s'%str(end-begin)
    Compared()
    return True